package com.wei.czz.framework.job;

import com.wei.czz.common.constant.Constant;
import com.wei.czz.common.constant.RedisConstant;
import com.wei.czz.common.enums.CommonEnum;
import com.wei.czz.framework.admin.entity.UserLoginEntity;
import com.wei.czz.framework.admin.manager.UserManager;
import com.wei.czz.framework.common.handler.redis.RedisZSetHandler;
import lombok.AllArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * Created by IntelliJ IDEA.
 *
 * @author wei
 * date: 2021-05-24 16:07:00
 * className: UserJob 用户定时器类
 * version: 1.0
 * description:
 */
@Component
@AllArgsConstructor
public class UserJob {

    private static final Logger log = LoggerFactory.getLogger(UserJob.class);

    private final UserManager userManager;

    private final RedisZSetHandler redisZSetHandler;

    /**
     * 每五分钟执行一次用户退出登录清理操作
     */
    @Scheduled(cron = "0 0/5 * * * ?")
//    @Scheduled(cron = "0/5 * * * * ?")
    public void userClear() {
        log.info("=====>>用户登录清除定时器开启<<=====");

        long now = System.currentTimeMillis();

        // 获取Redis保存的用户登录失效信息，条件为过期时间小于等于当前时间的记录
        Set<String> userSet =
                redisZSetHandler.rangeByScore(RedisConstant.OVER_TIME_ZSET, CommonEnum.ZERO.getValue(), now);
        log.info("待清除登录用户列表：{}", userSet);

        List<UserLoginEntity> userLoginList = new ArrayList<>(userSet.size());
        List<String> userKeyList = new ArrayList<>(userSet.size());

        for (String userKey : userSet) {
            String[] arr = userKey.split(Constant.SPLIT);

            try {
                long userId = Long.parseLong(arr[0]);
                int channel = Integer.parseInt(arr[1]);

                UserLoginEntity userLogin = new UserLoginEntity();
                userLogin.setUserId(userId)
                        .setChannel(channel);
                userLoginList.add(userLogin);

                userKeyList.add(userKey);
            } catch (NumberFormatException e) {
                log.error("用户值解析异常。message={}", e.getMessage());
            } catch (Exception e) {
                log.error("用户解析异常。message={} class={}", e.getMessage(), e.getClass());
            }
        }

        if (!userKeyList.isEmpty()) {
            String[] userIds = userKeyList.toArray(new String[0]);

            // 删除Redis保存的用户登录失败信息
            redisZSetHandler.remove(RedisConstant.OVER_TIME_ZSET, userIds);
        }
        if (!userLoginList.isEmpty()) {
            // 踢出登录
            userManager.kickLogin(userLoginList);
        }

        log.info("=====>>用户登录信息定时清除完毕<<=====");
    }
}
